package com.droidwatcher.modules.vk;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.provider.Settings;

import com.droidwatcher.JsonEntity.RunningAppInfo;
import com.droidwatcher.util.AXLog;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.USAGE_STATS_SERVICE;

/**
 * Created by Administrator on 2018/3/28.
 */

public class PackageModule {
    public static String TAG = "wzytest";
    Context context ;
    PackageManager pm ;
    public PackageModule(Context context) {
        this.context = context ;
    }

//    public void getPackageInfo(){
//        PackageManager packageManager = context.getPackageManager();
//        packageManager.getInstalledApplications(PackageManager.GET_CONFIGURATIONS);
//    }

//    public String getForegroundApp(Context context) {
//        List<ActivityManager.RunningAppProcessInfo> lr= context.getRunningAppProcesses();
//
//        if  (lr == null)  {
//            return null;
//        }
//        for (ActivityManager.RunningAppProcessInfo ra : lr) {
//            if (ra.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE   || ra.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
//                return ra.processName;
//            }
//        }
//        return null;
//    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private String getForegroundApp2(Context context) {
        UsageStatsManager usageStatsManager = (UsageStatsManager) context.getSystemService(USAGE_STATS_SERVICE); //Context.USAGE_STATS_SERVICE

        long ts = System.currentTimeMillis();
        List<UsageStats> queryUsageStats =
                usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST,ts-2000, ts);
        if (queryUsageStats == null || queryUsageStats.isEmpty())  {
            return null;
        }
        UsageStats recentStats = null;
        for (UsageStats usageStats : queryUsageStats) {
            if(recentStats == null || recentStats.getLastTimeUsed() < usageStats.getLastTimeUsed()) {
                recentStats = usageStats;
            }
        }
        return recentStats.getPackageName();
    }


    public ArrayList<RunningAppInfo> getAppInfos(){
        AXLog.e("wzytest","run in android.os.Build.VERSION.SDK_INT:"+android.os.Build.VERSION.SDK_INT);
        ArrayList<RunningAppInfo> infos = new ArrayList<>();
        if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
            Calendar beginCal = Calendar.getInstance();
            beginCal.add(Calendar.HOUR_OF_DAY, -1);
            Calendar endCal = Calendar.getInstance();
            UsageStatsManager manager=(UsageStatsManager)context.getApplicationContext().getSystemService(USAGE_STATS_SERVICE);
            List<UsageStats> stats= null;
            stats = manager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY,beginCal.getTimeInMillis(),endCal.getTimeInMillis());
            if(stats==null){
                context.startActivity(new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS));
            }
            if(stats!=null){
                for (UsageStats stat:stats){
                    AXLog.e("wzytest",stat.getPackageName()+" getFirstTimeStamp:"+stat.getFirstTimeStamp()+" stat.getLastTimeUsed():"+stat.getLastTimeUsed()+" getTotalTimeInForeground:"+stat.getTotalTimeInForeground());
                    RunningAppInfo info = new RunningAppInfo();

                    info.setPkgName(stat.getPackageName());
                    info.setDuration(stat.getTotalTimeInForeground());
                    info.setUse_date(stat.getLastTimeUsed());
                    try {
                        pm = context.getPackageManager();
                        ApplicationInfo application=pm.getPackageInfo(stat.getPackageName(), 0).applicationInfo;
                        String applicationName = (String) pm.getApplicationLabel(application);
                        info.setAppName(applicationName);
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }
                    infos.add(info);
                }
            }
        }
        return infos;
    }

    // 查询所有正在运行的应用程序信息： 包括他们所在的进程id和进程名
    // 这儿我直接获取了系统里安装的所有应用程序，然后根据报名pkgname过滤获取所有真正运行的应用程序
    public List<RunningAppInfo> queryAllRunningAppInfo() {
        pm = context.getPackageManager();
        // 查询所有已经安装的应用程序
        List<ApplicationInfo> listAppcations = pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
        Collections.sort(listAppcations,new ApplicationInfo.DisplayNameComparator(pm));// 排序

        // 保存所有正在运行的包名 以及它所在的进程信息
        Map<String, ActivityManager.RunningAppProcessInfo> pgkProcessAppMap = new HashMap<String, ActivityManager.RunningAppProcessInfo>();

        ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        // 通过调用ActivityManager的getRunningAppProcesses()方法获得系统里所有正在运行的进程
        List<ActivityManager.RunningAppProcessInfo> appProcessList = mActivityManager
                .getRunningAppProcesses();

        for (ActivityManager.RunningAppProcessInfo appProcess : appProcessList) {
            int pid = appProcess.pid; // pid

            String processName = appProcess.processName; // 进程名
            AXLog.e(TAG, "processName: " + processName + "  pid: " + pid);

            String[] pkgNameList = appProcess.pkgList; // 获得运行在该进程里的所有应用程序包

            // 输出所有应用程序的包名
            for (int i = 0; i < pkgNameList.length; i++) {
                String pkgName = pkgNameList[i];
                AXLog.e(TAG, "packageName " + pkgName + " at index " + i+ " in process " + pid);
                // 加入至map对象里
                pgkProcessAppMap.put(pkgName, appProcess);
            }
        }
        // 保存所有正在运行的应用程序信息
        List<RunningAppInfo> runningAppInfos = new ArrayList<RunningAppInfo>(); // 保存过滤查到的AppInfo

        for (ApplicationInfo app : listAppcations) {
            // 如果该包名存在 则构造一个RunningAppInfo对象
            if (pgkProcessAppMap.containsKey(app.packageName)) {
                // 获得该packageName的 pid 和 processName
                int pid = pgkProcessAppMap.get(app.packageName).pid;
                String processName = pgkProcessAppMap.get(app.packageName).processName;

                runningAppInfos.add(getAppInfo(app, pid, processName));
            }
        }

        return runningAppInfos;

    }

    // 构造一个RunningAppInfo对象 ，并赋值
    private RunningAppInfo getAppInfo(ApplicationInfo app, int pid, String processName) {
        RunningAppInfo appInfo = new RunningAppInfo();
        appInfo.setAppLabel((String) app.loadLabel(pm));
        appInfo.setAppIcon(app.loadIcon(pm));
        appInfo.setPkgName(app.packageName);
        appInfo.setPid(pid);
        appInfo.setProcessName(processName);
        return appInfo;
    }


}
